$(function(){
	$('input[name="begDt"], input[name="endDt"]').datepicker({
		format: "yyyy-mm-dd",
	    todayBtn: "linked",
	    language: "zh-CN",
	    autoclose: true,
	    todayHighlight: true
	});

	var today = getDay(0);
	var yesterday = getDay(-1);
	$('input[name="begDt"]').val(yesterday);
	$('input[name="endDt"]').val(today);
});

var myApp = angular.module('myApp', [ 'ngGrid', 'ui.select2' ]);
myApp.controller('orderMonitorCtrl', function($scope, $http) {
	//global variable
	$scope.selectedRows = [];
	//init page item
	$scope.init = function() {
		$('input[name="backDt"]').datetimepicker({
			format: "yyyy-mm-dd hh:ii",
		    todayBtn: "linked",
		    language: "zh-CN",
		    forceParse: false,
		    autoclose: true,
		    todayHighlight: true
		});
		$scope.stList = [{"id":0, "lb":"在用"},{"id":1, "lb":"停用"}];
		httpPost($http, {"url":ctx+"/client/findListByFirst", "data": {"ffMap":{"st":0}}}, function(data){
			$scope.clientList=data.dt;
		}, function(){
			toastError("初始化客户列表失败。");
		});
		httpPost($http, {"url":ctx+"/dict/findListBy", "data": {"ffMap":{"cd":"receiptStatus","st":0}}}, function(data){
			$scope.statusList = data.dt;
		}, function(){
			toastError("初始化承包类型列表失败。");
		});
	};
	$scope.init();
	
	//grid
	$scope.pagingOptions = {
		pageSizes : [ 20, 50, 100 ],
		pageSize : 20,
		currentPage : 1,
		onQueryFlag : false
	};
	$scope.$watch('pagingOptions', function(newVal, oldVal) {
		if (newVal !== oldVal/* && newVal.currentPage !== oldVal.currentPage*/) {
			$scope.query();
		}
	}, true);
	$scope.gridOptions = {
		data : 'dt',
		totalServerItems : 'tt',
		
		columnDefs : [
		{
			field : "id",
			displayName : "ID", visible : false
		},
		{
			field : "orderId",
			displayName : "orderId", visible : false
		},
		{
			field : "clientName",
			displayName : "客户",width:160
		},
		{
			field : "orderCd",
			displayName : "订单编号",width:160
		},
		{
			field : "legsCd",
			displayName : "分段订单号",width:160
		},
		{
			field : "cd",
			displayName : "回单编号",width:160
		},
		{
			field : "constractorName",
			displayName : "承运商简称",width:160
		},
		{
			field : "vocationName",
			displayName : "业务类型",width:160
		},
		{
			field : "statusName",
			displayName : "回单状态",width:160
		},
		{
			field : "quantity",
			displayName : "数量",width:160
		},
		{
			field : "carNo",
			displayName : "车牌号",width:160
		},
		{
			field : "driverName",
			displayName : "司机",width:160
		},
		{
			field : "freceiverName",
			displayName : "发货方",width:160
		},
		{
			field : "treceiverName",
			displayName : "收货方",width:160
		},
		{
			field : "arriveDt",
			displayName : "运抵时间",width:160,
			cellFilter: "date:'yyyy-MM-dd HH:mm:ss'"
		},
		{
			field : "mustDt",
			displayName : "应回单时间",width:160,
			cellFilter: "date:'yyyy-MM-dd HH:mm:ss'"
		},
		{
			field : "backDt",
			displayName : "已返还时间",width:160,
			cellFilter: "date:'yyyy-MM-dd HH:mm:ss'"
		},
		{
			field : "reason",
			displayName : "延时原因",width:255
		},
		{
			field : "shipmentCd",
			displayName : "调度单号",width:160
		}
		],
		enablePaging : true,
		pagingOptions : $scope.pagingOptions,
		enableCellEdit:true,
		//enablePinning : true,
		//showColumnMenu : true,
		//showGroupPanel : true,
		showSelectionCheckbox : true,
		selectedItems : $scope.selectedRows,
		plugins : [ /*new ngGridFlexibleHeightPlugin()*/ ],
		i18n: 'zh-cn', rowHeight : 20.2, footerRowHeight : 35,
		showFooter : true
	};

	$scope.query = function() {
		closeModal($("#queryFormModal"));
		hideShadow();
		var requestBody = {
			pageNb : $scope.pagingOptions.currentPage,
			pageSize : $scope.pagingOptions.pageSize,
			ffMap : $scope.queryForm
		};
		setTimeout(function() {
			httpPost($http, {"url":ctx + '/orderMonitor/findListBy', "data":requestBody, "ifBlock":true}, function(data){
				$scope.tt = data.tt;
				$scope.dt = data.dt;
				
				$scope.gridOptions.$gridScope.toggleSelectAll(false);
			}, function(errMsg){
				toastError("查询失败。" + errMsg);
			});
		}, 100);
	};
	//trigger query when currentPage not change
	$scope.onQuery = function(){
		$scope.pagingOptions.onQueryFlag = !$scope.pagingOptions.onQueryFlag;
		$scope.pagingOptions.currentPage = 1;
	};

	$scope.refresh=function(){
		hideShadow();
		$scope.onQuery();	
	};

	//utils
	$scope.onClearSelectedRows = function() {
		$scope.gridOptions.$gridScope.toggleSelectAll(false);
	};
	
	//crud
	$scope.onOpenQueryFormModal = function() {
		hideShadow();
		openModal($("#queryFormModal"));
	};
	
	//返单确认
	$scope.orderReturn = function() {
		if($scope.selectedRows.length< 1) { toastWarning("请至少选择一笔记录进行确认。"); return; }
		$scope.editFormRt={};
		var date= (new Date());
		var now = date.getFullYear() + "-" + (parseInt(date.getMonth()) + 1) +"-"+((date.getDate() > 9) ? date.getDate() : "0" + date.getDate())+" "+((date.getHours()> 9) ? date.getHours() : "0" + date.getHours())+":"+((date.getMinutes() > 9) ? date.getMinutes() : "0" + date.getMinutes());
		$scope.editFormRt.backDt=now;
		hideShadow();
		openModal($("#returnModal"));
	};
	
	$scope.receipt=function(){
		closeModal($("#returnModal"));
		var selectedRowsId = [];
		var selectedRowsOrderId = [];
		$.each($scope.selectedRows, function(idx, obj){
			selectedRowsId.push(obj.id);
			selectedRowsOrderId.push(obj.orderId);
		});
		httpPost($http, {"url":ctx + '/orderMonitor/updStByIds',"params":{"ids":selectedRowsId,"orderIds":selectedRowsOrderId,"backDt":$scope.editFormRt.backDt}, "ifBlock":true}, function(data){
			$scope.onQuery();
		});
	};
	
	//延时单确认
	$scope.onOpenNntConfirmModal = function(){
		hideShadow();
		openModal($("#nntModal"));
	};
	
	$scope.nntConfirm = function(){
		closeModal($("#nntModal"));
		var selectedRowsId = [];
		$.each($scope.selectedRows, function(idx, obj){
			selectedRowsId.push(obj.id);
		});
		httpPost($http, {"url":ctx + '/orderMonitor/updReasonByIds',"params":{"ids":selectedRowsId,"reason":$scope.editFormNnt.reason}, "ifBlock":true}, function(data){
			$scope.onQuery();
		});
	};
	
	$scope.onOpenEditFormModal = function(type, id) {
		if(type=="add"){
			$scope.editForm = {};
		}else if(type=="upd"){
			//if($scope.selectedRows.length != 1) { toastWarning("请选择一笔记录进行编辑。"); return; }
			httpGet($http, {"url":ctx+'/orderMonitor/id/'+id, "ifBlock":true}, function(data){
				$scope.editForm = data.dt;
			}, function(errMsg){
				toastWarning("查询此笔记录失败。");
			});
		}
		openModal($("#editFormModal"));
	};
	$scope.onSaveEditForm = function(){
		closeModal($("#editFormModal"));
		httpPost($http, {"url":ctx + '/orderMonitor/save', "data":$scope.editForm, "ifBlock":true}, function(data){
			toastSuccess("保存成功");
			$scope.query();
		}, function(errMsg){
			toastError("保存失败。" + errMsg);
		});
	};
	$scope.onOpenDelFormModal = function() {
		var selectedRowsLength = $scope.selectedRows.length;
		if(selectedRowsLength < 1) { toastWarning("请至少选择一笔记录进行删除。"); return; }
		dialogConfirm("是否确认删除选择的"+selectedRowsLength+"笔记录？", function(){
			var selectedRowsId = [];
			$.each($scope.selectedRows, function(idx, obj){
				selectedRowsId.push(obj.id);
			});
			
			httpPost($http, {"url":ctx + '/orderMonitor/updStByIds', "params":{"ids":selectedRowsId, "st":1}, "ifBlock":true}, function(data){
				toastSuccess("删除成功");
				$scope.query();
			}, function(errMsg){
				toastError("删除失败。" + errMsg);
			});
		});
	};
	//右键菜单功能
	$('#mainDataBlock').contextMenu('menu', {
	      //菜单项样式
	      itemStyle: {
	        fontFamily : 'verdana',
	        backgroundColor : '#F0F0F0',
	        border: 'none',
	        padding: '4px'
	      },
	      //菜单项鼠标放在上面样式
	      itemHoverStyle: {
	        border: '1px solid #fff'
	      },
	      onShowMenu: function(e, menu) {
	    	  var sts =[];
				for(var i=0;i<$scope.selectedRows.length;i++){
					var st = $scope.selectedRows[i]['status'];
					if(jQuery.inArray( st, sts ) < 0){
						sts.push(st);
					}
				}
				if($scope.selectedRows.length===0){
					$('#return, #nnt', menu).remove();
				}else{
					if(sts.length==1){
						if(sts[0]=='RETURN'||sts[0]=='RCP'){
							$('#return, #nnt', menu).remove();
						}else if(sts[0]=='NNT'){
							$('#nnt', menu).remove();
						}
					}else{
						$('#return, #nnt', menu).remove();
					}
				}
	        return menu;
	      }
		});
});